package lex.netant;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadThread extends Thread {
	String sourceFile;
	String objName;
	int code;
	long startPos, stopPos;
	// long nStart=0;//
	// long nStop;//
	RandomOutputStream dl;
	// Reload rl;
	URL url;
	int num;
	HttpURLConnection con;
	// JProgressBar pb;
	InputStream input;

	public DownloadThread(String sourceFile, String objName, long startPos, long stopPos, int num) {
		this.sourceFile = sourceFile;
		this.objName = objName;
		this.num = num;
		this.startPos = startPos;
		this.stopPos = stopPos;
		// pb=javaants.getProgressBar();
		// pb.setMinimum(0);
		try {
			// rl=new Reload(Utility.getTempFileName()+"."+"tmp");
			// rl.serializeIn();
			dl = new RandomOutputStream(objName, startPos);
			url = new URL(sourceFile);
			String p = "bytes=" + startPos + "-";
			con = (HttpURLConnection) url.openConnection();
			con.setRequestProperty("GET", "HTTP/1.1");
			con.setRequestProperty("User-Agent", "xdj");
			con.setRequestProperty("Accept", "*/*");
			con.setRequestProperty("Accept-Language", "zh-cn");
			con.setRequestProperty("Accept-Encoding", "gzip,defate");
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("RANGE", p);
			// Utility.nStop=con.getContentLength();
			code = con.getResponseCode();
			// pb.setMaximum((int)(Utility.nStop+Utility.nStart));
			System.out.println("startPos:" + Utility.nStart[num]);//
			System.out.println("code:" + code);
			// Utility.nStop+=Utility.nStart;
			// System.out.println("nStop:"+Utility.nStop);//
			input = con.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		// while(nStart <= nStop){
		try {
			byte[] b = new byte[1024];
			int nRead;
			while (((nRead = input.read(b, 0, 1024)) > 0) && (startPos < stopPos) && (!Utility.stop)) {
				startPos += dl.write(b, 0, nRead);
			}
			Utility.nStart[num] = startPos;
			Utility.nStop[num] = stopPos;
			Utility.bStop[num] = true;
			System.out.println("Utility.bStop" + num + ":" + Utility.bStop[num]);
			dl.close();
		} catch (Exception e) {
			Utility.nStart[num] = startPos;
			Utility.nStop[num] = stopPos;
			Utility.bStop[num] = true;
			// javaants.setStopFalse();
			// javaants.setStartTrue();
			Utility.bStop[num] = true;
			System.out.println("In Exception Utility.bStop" + num + ":" + Utility.bStop[num]);
			e.printStackTrace();
		}
		// System.out.println("nStart:"+Utility.nStart);
		// }
	}
}
